package sunbao.ido.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-12-14
 * \* Time: 15:56
 * \* Description:
 * \
 */
@Controller
@EnableScheduling
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    // MessageMapping websocket映射
    @MessageMapping("/send")
    // @SendTo定义了消息的目的地(PS:只是起到定义的作用)。“接收/app/send发来的value，然后将value转发到/topic/send客户端。
    @SendTo("/topic/send")
    public SocketMessage send(SocketMessage message) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        message.date = df.format(new Date());
        // 发送至订阅该路径的客户端
        messagingTemplate.convertAndSend("/topic/queue", message);
        return message;
    }

    @Scheduled(fixedRate = 1000)
    public void callback() throws MessagingException {
        // 发现消息
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messagingTemplate.convertAndSend("/topic/callback", df.format(new Date()));
    }

}